<template>
  <div class="storeorder-page page-main">
    <search-form :model="searchParams" @search="search">
      <a-form-item label="订单状态：" class="width100">
        <a-radio-group v-model:value="searchParams.status" button-style="solid" class="mr20" @change="search(false)">
          <a-radio-button value="all">全部 {{ '(' + orderTypes.all ? orderTypes.all : 0 + ')' }}</a-radio-button>
          <a-radio-button value="unPaid">
            未支付
            {{ '(' + orderTypes.unPaid ? orderTypes.unPaid : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="notShipped">
            未发货
            {{ '(' + orderTypes.notShipped ? orderTypes.notShipped : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="spike">待收货 {{ '(' + orderTypes.spike ? orderTypes.spike : 0 + ')' }}</a-radio-button>
          <a-radio-button value="bargain">
            待评价
            {{ '(' + orderTypes.bargain ? orderTypes.bargain : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="complete">
            交易完成
            {{ '(' + orderTypes.complete ? orderTypes.complete : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="toBeWrittenOff">
            待核销
            {{ '(' + orderTypes.toBeWrittenOff ? orderTypes.toBeWrittenOff : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="refunding">
            退款中
            {{ '(' + orderTypes.refunding ? orderTypes.refunding : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="refunded">
            已退款
            {{ '(' + orderTypes.refunded ? orderTypes.refunded : 0 + ')' }}
          </a-radio-button>
          <a-radio-button value="deleted">
            已删除
            {{ '(' + orderTypes.deleted ? orderTypes.deleted : 0 + ')' }}
          </a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="时间选择：" class="width100">
        <a-radio-group v-model:value="searchParams.dateLimit" button-style="solid" class="mr20"
          @change="selectChange(searchParams.dateLimit)">
          <a-radio-button v-for="(item, i) in DAYS_TYPE" :key="i" :value="item.value">
            {{ item.label }}
          </a-radio-button>
        </a-radio-group>
        <a-range-picker v-model:value="timeVal" value-format="YYYY-MM-DD" />
      </a-form-item>
      <a-form-item label="订单号：" name="prop">
        <a-input v-model:value="searchParams.orderNo" placeholder="请输入" />
      </a-form-item>
    </search-form>
    <div class="table-toolbar">
      <!-- <add-button @click="add()" /> -->
      <a-button type="primary">导出</a-button>
    </div>
    <g-table ref="tableRef" :columns="columns" row-key="orderId" :api="getPageList" :params="searchParams" />

    <storeorderDetail v-model:visible="visible" :data="activeRow" @change="search(false)" />
    <orderSend v-model:visible="isSend" :orderId="activeRow.orderId" @change="search(false)" />
    <orderlog v-model:visible="isLog" :orderId="activeRow.orderId" />
    <a-modal v-model:visible="ismark" title="订单备注" :width="800" @ok="changeMark">
      <a-textarea v-model:value="activeRow.remark" :auto-size="{ minRows: 2, maxRows: 5 }" placeholder="请输入" />
    </a-modal>
    <a-modal v-model:visible="isRefuse" title="拒绝退款原因" :width="800" @ok="RefusehandlerSubmit">
      <a-textarea v-model:value="activeRow.reason" :auto-size="{ minRows: 2, maxRows: 5 }" placeholder="请输入" />
    </a-modal>
    <a-modal v-model:visible="isrefund" title="退款处理" :width="800" @ok="refundhandlerSubmit">
      <a-input-number id="inputNumber" v-model:value="activeRow.amount" :min="1" :max="activeRow.payPrice" />
    </a-modal>
  </div>
</template>

<script setup lang="tsx">
import { storeorderDel, getPageList, orderStatusNumApi, writeUpdateApi, orderMarkApi, orderRefuseApi, orderRefundApi, orderDeleteApi } from './api';
import { orderType, type IorderType, type Istoreorder } from './entity';
import storeorderDetail from './detail.vue';
import orderSend from './orderSend.vue';
import orderlog from './orderlog.vue';
import { DAYS_TYPE } from "@/utils/constant";
import { Modal } from 'ant-design-vue';
const searchParams = reactive({
  storeId: "",
  keywords: "",
  dateLimit: "",
  date: "",
  status: 'all',
  type: 0,
  orderNo: ''
});
let timeVal = $ref<string[]>(["", ""]);
let visible = $ref(false)
let isSend = $ref(false)
let isLog = $ref(false)
let ismark = $ref(false)
let isRefuse = $ref(false)
let isrefund = $ref(false)

let orderTypes = $ref<IorderType>(new orderType())
const { tableRef, columns, search } = useTable<Istoreorder>([

  { title: '订单号', dataIndex: 'orderId' },
  { title: '订单类型', dataIndex: 'orderType' },
  { title: '收货人', dataIndex: 'realName' },
  {
    title: '商品信息', dataIndex: 'productList',
    customRender: ({ record }) => (
      <>
        <a-popover trigger="hover" placement="right" >

          {
            record.productList && record.productList.length && (<div class="pup_card" >

              {
                record.productList.map((val, i) => {

                  return (< div key={i} class="tabBox acea-row row-middle" style="flex-wrap: inherit;" >
                    <div class="">
                      <span class="tabBox_tit mr10">{val.info.productName + ' | '}{val.info.sku ? val.info.sku : '-'}</span>
                      <span class="tabBox_pice">{'￥' + val.info.price ? val.info.price + ' x ' + val.info.payNum : '-'}</span>
                    </div>
                  </div>)
                })
              }


            </div>)
          }

        </a-popover >
      </>
    ),
  },
  { title: '实际支付', dataIndex: 'payPrice' },
  { title: '支付方式', dataIndex: 'payTypeStr' },
  {
    title: '订单状态', dataIndex: 'total_num',
    customRender: ({ record }) => (
      <>
        <div v-if={record.refundStatus === 1 || record.refundStatus === 2} class="refunding" >
          <template>
            <a-popover trigger="hover" placement="left">
              <b style="color: #f124c7;" slot="reference">{record.statusStr?.value}</b>
              <div class="pup_card flex-column">
                <span>退款原因：{record.refundReasonWap}</span>
                <span>备注说明：{record.refundReasonWapExplain}</span>
                <span>退款时间：{record.refundReasonTime}</span>
                <span class="acea-row">
                  退款凭证：
                  {record.refundReasonWapImg && (<template v-if={record.refundReasonWapImg}>
                    {
                      record.refundReasonWapImg.map((item, i) => {
                        <div key={i} class="demo-image__preview" style="width: 35px;height: auto;display: inline-block;">
                          <a-image src={item} review-src-list={[item]}
                          />
                        </div>
                      })
                    }

                  </template>)}

                  <span v-else style="display: inline-block">无</span>
                </span>
              </div>
            </a-popover>
          </template>
        </div>
        <span v-else>{record.statusStr.value}</span>
      </>
    ),
  },
  { title: '下单时间', dataIndex: 'createTime' },
  {
    title: '操作',
    dataIndex: 'op',
    customRender: ({ record }) => (
      <>

        {/* <table-button v-if={record.paid === false} onClick={() => edit(record)}>编辑</table-button> */}
        {record.statusStr.key === 'notShipped' && record.refundStatus === 0 && <table-button onClick={() => sendOrder(record)}>发送货</table-button>}
        {record.statusStr.key === 'toBeWrittenOff' && record.paid == true && record.refundStatus === 0 && <table-button onClick={() => onWriteOff(record)}>立即核销</table-button>}
        <table-button onClick={() => onOrderDetails(record)}>订单详情</table-button>
        <table-button onClick={() => onOrderLog(record)}>订单记录</table-button>
        <table-button onClick={() => onOrderMark(record)}>订单备注</table-button>
        {record.refundStatus === 1 && (<><table-button onClick={() => onOrderRefuse(record)}>拒绝退款</table-button>
          <table-button onClick={() => onOrderRefund(record)}>立即退款</table-button>
          <table-button onClick={() => remove(record)}>删除订单</table-button></>)}
        {record.statusStr.key !== 'unPaid' && <table-button onClick={() => onOrderPrint(record)}>打印小票</table-button>
        }
      </>
    )
  }
])
onMounted(() => {
  queryNum()
})
async function queryNum() {
  let { dateLimit, type } = searchParams
  let list = await orderStatusNumApi({ dateLimit, type })
  orderTypes = list
}
// 选择时间
function selectChange(tab: string) {
  searchParams.date = tab;
  timeVal = [];
  search(false);
}
let activeRow = $ref<Partial<Istoreorder>>({})
function edit(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  visible = true
}
function onOrderDetails(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  visible = true
}
function onOrderLog(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  isLog = true
}
function onOrderMark(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  ismark = true
}
async function changeMark() {
  let { remark: mark, orderId: orderNo } = activeRow
  await orderMarkApi({ mark, orderNo })
  AntMessage.success('操作成功')
  search(false)
  ismark = false
}
function onOrderRefuse(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  isRefuse = true
}
async function RefusehandlerSubmit(row: Partial<Istoreorder> = {}) {
  let { reason, orderId: orderNo } = activeRow
  await orderRefuseApi({ reason, orderNo })
  search(false)
  isRefuse = false
}
function onOrderRefund(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  isrefund = true
}

async function refundhandlerSubmit(row: Partial<Istoreorder> = {}) {
  let { amount, orderId: orderNo } = activeRow
  await orderRefundApi({ amount, orderNo })
  search(false)
  isrefund = false
}
function onOrderPrint(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  visible = true
}
function sendOrder(row: Partial<Istoreorder> = {}) {
  activeRow = { ...row }
  if (row.type === 0) {
    isSend = true
  }


}
function onWriteOff(row: Partial<Istoreorder> = {}) {
  Modal.confirm({
    title: '提示',
    content: '核销订单吗',
    onOk() {
      writeUpdateApi(row.verifyCode).then(() => {
        AntMessage.success("核销成功");
        search(false)
      })
    },
  });
}
function remove(row: Partial<Istoreorder> = {}) {
  if (row.isDel) {
    Modal.confirm({
      title: '提示',
      content: '删除订单吗',
      onOk() {
        orderDeleteApi({ orderNo: row.orderId }).then(() => {
          AntMessage.success('删除成功')
          search(false)
        })
      }
    })
  } else {
    AntMessage.error('您选择的的订单存在用户未删除的订单，无法删除用户未删除的订单！')
  }
}
</script>

<style lang="scss"></style>